package com.atyuntuku.yuntuku.controller.picture;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.atyuntuku.yuntuku.annotation.AuthCheck;
import com.atyuntuku.yuntuku.common.BaseResponse;
import com.atyuntuku.yuntuku.common.ResultUtils;
import com.atyuntuku.yuntuku.controller.request.DeleteRequest;
import com.atyuntuku.yuntuku.controller.request.PictureEditRequest;
import com.atyuntuku.yuntuku.controller.request.PictureQueryRequest;
import com.atyuntuku.yuntuku.controller.request.PictureUpdateRequest;
import com.atyuntuku.yuntuku.dto.file.PictureUploadRequest;
import com.atyuntuku.yuntuku.dto.file.UploadPictureResult;
import com.atyuntuku.yuntuku.exception.ErrorCode;
import com.atyuntuku.yuntuku.exception.ThrowUtils;
import com.atyuntuku.yuntuku.manager.COSManager;
import com.atyuntuku.yuntuku.mapper.UserMapper;
import com.atyuntuku.yuntuku.pojo.Picture;
import com.atyuntuku.yuntuku.pojo.User;
import com.atyuntuku.yuntuku.service.PictureService;
import com.atyuntuku.yuntuku.service.UserService;
import com.atyuntuku.yuntuku.utils.CommonUtils;
import com.atyuntuku.yuntuku.vo.PictureTagCategory;
import com.atyuntuku.yuntuku.vo.PictureVO;
import com.atyuntuku.yuntuku.vo.UserVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.UploadPartRequest;
import com.qcloud.cos.utils.IOUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.pqc.jcajce.provider.qtesla.SignatureSpi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * ClassName: FileController
 * Package: com.atyuntuku.yuntuku.controller.picture
 * Description:
 *
 * @Author qinglong wei
 * @Create 2025/10/9 22:02
 * @Version 1.0
 */
@Api(tags = "图片模块")
@RestController
@RequestMapping("/picture")
@Slf4j
public class FileController {
    @Autowired
    COSManager cosManager;

    @Autowired
    PictureService pictureService;

    @Autowired
    UserMapper userMapper;

    @AuthCheck(mustAuth = "admin")
    @PostMapping("/test/upload")
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile file) {
        String filepath = String.format("/test/%s", file.getOriginalFilename());
        File tempFile = null;
        try {
            tempFile = File.createTempFile(filepath, null);
            file.transferTo(tempFile);
            PutObjectResult putObjectResult = cosManager.putObject(filepath, tempFile);
        } catch (IOException e) {
            log.error("file upload error , reason : {}", e.getMessage());
            ResultUtils.error(ErrorCode.OPERATION_ERROR, "上传失败");
        } finally {
            if (tempFile != null) {
                boolean flag = tempFile.delete();
                if (!flag) {
                    log.error("Delete error , filepath : {}", tempFile.getAbsolutePath());
                }
                ThrowUtils.throwIf(!flag, ErrorCode.SYSTEM_ERROR, "系统删除错误");
            }
        }
        return ResultUtils.success(filepath.toString());
    }


    @AuthCheck(mustAuth = "admin")
    @GetMapping("/test/download")
    public void testUloadFile(@RequestParam String filepath, HttpServletResponse response) throws IOException {

        COSObject cosObject = cosManager.getObject(filepath);
        COSObjectInputStream inputStream = cosObject.getObjectContent();

        try {
            byte[] bytes = null;
            bytes = IOUtils.toByteArray(inputStream);
            response.setHeader("Content-Disposition", "attachment;filename=" + filepath);
            response.setContentType("application/octet-stream;charset=UTF-8");
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
        } catch (IOException e) {
            ResultUtils.error(ErrorCode.OPERATION_ERROR, "下载失败");
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }


    @AuthCheck(mustAuth = "admin")
    @PostMapping("/upload")
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile, PictureUploadRequest pictureUploadRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, request);
        return ResultUtils.success(pictureVO);
    }

    //普通用户使用
    @PostMapping("/getpagesvo")
    public BaseResponse<Page<PictureVO>> getPagesVO(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        return ResultUtils.success(pictureService.getPicturePage(pictureQueryRequest));
    }

    //管理员使用
    @AuthCheck(mustAuth = "admin")
    @PostMapping("/getpages")
    public BaseResponse<Page<Picture>> getPages(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {

        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        Page<Picture> page = pictureService.page(new Page<>(current, pageSize), pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(page);
    }

    //根据id查图片（管理员可用）
    @AuthCheck(mustAuth = "admin")
    @PostMapping("/getbypictureid")
    public BaseResponse<Picture> getPictureByid(@RequestParam Long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR, "参数错误");
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);

        return ResultUtils.success(picture);
    }

    //根据id查图片
    @PostMapping("/getbypicturevoid")
    public BaseResponse<PictureVO> getPictureVOByid(@RequestParam Long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR, "参数错误");
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        PictureVO pictureVO = PictureVO.objToVo(picture);
        User user = userMapper.selectById(picture.getUserId());
        ThrowUtils.throwIf(user == null,ErrorCode.NOT_FOUND_ERROR,"请求数据不存在，或者图片上传者所传内容被禁止");
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user,userVO);
        pictureVO.setUser(userVO);
        return ResultUtils.success(pictureVO);
    }

    //更新图片（管理员端）
    @AuthCheck(mustAuth = "admin")
    @PostMapping("/update")
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest) {
        return ResultUtils.success(pictureService.updatePicture(pictureUpdateRequest));
    }


    //删除图片
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePictureByid(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null, ErrorCode.PARAMS_ERROR, "参数不能为空");
        Long id = deleteRequest.getId();
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR, "图片id不合法");

        User currentUser = CommonUtils.getCurrentUser(request);
        ThrowUtils.throwIf(currentUser == null, ErrorCode.NOT_LOGIN_ERROR, "用户未登录");

        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);

        //删除图片鉴权（不是用户本人或者管理员账户就禁止删除）
        ThrowUtils.throwIf(picture.getUserId() != currentUser.getId() && !CommonUtils.isAdmin(currentUser), ErrorCode.NO_AUTH_ERROR, "无权限删除");

        boolean flag = pictureService.removeById(id);
        return ResultUtils.success(flag);
    }

    @PostMapping("/editpicture")
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest ,HttpServletRequest request )
    {
        return  ResultUtils.success(pictureService.editPicture(pictureEditRequest,request));
    }

    @GetMapping("/tagcategory")
    public BaseResponse<PictureTagCategory> getTagsAndCategory(){
        List<String> tagList = Arrays.asList("热门","搞笑","生活","高清","艺术","校园","背景","创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");

        PictureTagCategory pictureTagCategory = new PictureTagCategory(tagList,categoryList);
        return  ResultUtils.success(pictureTagCategory);
    }
}
